package com.pf.controller;

import com.pf.dto.ResultResp;
import com.pf.dto.TaskDO;
import com.pf.utils.ResultRespUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2023/3/6 22:15
 */
@RestController
@RequestMapping("/task")
public class TaskController {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 测试按照字段顺序进行校验
     * <p>
     * 测试案例：
     * <p>
     * url：http://localhost:8080/task/add
     * <p>
     * {
     * "criteriaName":"审核准则名称1",
     * "firstCategory":"一级分类11",
     * "secondCategory":"二级分类22",
     * "thirdCategory":"三级分类33"
     * }
     *
     * @param task
     * @return
     */
    @PostMapping("/add")
    public ResultResp add(@RequestBody TaskDO task) {
        // 按照实体类字段顺序校验
        List<String> fieldNames = Arrays.stream(TaskDO.class.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        System.out.println(fieldNames);
        for (String fieldName : fieldNames) {
            Set<ConstraintViolation<TaskDO>> validateSet = validator.validateProperty(task, fieldName);
            for (ConstraintViolation violation : validateSet) {
                String propertyPath = violation.getPropertyPath().toString();
                System.out.println(propertyPath + ":" + violation.getMessage());
            }
        }
        return ResultRespUtils.success(task);
    }
}
